package com.wfh.easychat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfh.easychat.common.ErrorCode;
import com.wfh.easychat.exception.BusinessException;
import com.wfh.easychat.model.entity.GroupInfo;
import com.wfh.easychat.model.entity.UserContact;
import com.wfh.easychat.model.entity.UserInfo;
import com.wfh.easychat.model.enums.GroupJoinTypeEnum;
import com.wfh.easychat.model.enums.UserContactStatusEnum;
import com.wfh.easychat.model.vo.GroupInfoVo;
import com.wfh.easychat.service.GroupInfoService;
import com.wfh.easychat.mapper.GroupInfoMapper;
import com.wfh.easychat.service.UserContactService;
import com.wfh.easychat.service.UserInfoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
* @author fenghuanwang
* @description 针对表【group_info】的数据库操作Service实现
* @createDate 2025-09-29 18:19:23
*/
@Service
public class GroupInfoServiceImpl extends ServiceImpl<GroupInfoMapper, GroupInfo>
    implements GroupInfoService{

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private UserContactService userContactService;

    /**
     * 添加群组
     *
     * @param groupName
     * @param groupNotice
     * @param enumByValue
     * @return
     */
    @Override
    public GroupInfoVo addGroup(String groupName, String groupNotice, GroupJoinTypeEnum enumByValue, HttpServletRequest request, MultipartFile avata) {
        // 获取当前登录用户
        UserInfo loginUser = userInfoService.getLoginUser(request);
        Long userId = loginUser.getId();
        // 根据用户id查询该用户所创建的群组数量
        LambdaQueryWrapper<GroupInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupInfo::getGroupOwner, userId);
        long count = this.count(queryWrapper);
        if (count > 10L) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能创建10个群");
        }
        try {
            avata.transferTo(new File(System.getProperty("user.dir") + File.separator + "groupavata"));
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        String originalFilename = avata.getOriginalFilename();
        String avataUrl = "http://localhost:8080/api/static/avata/" + System.getProperty("user.dir") + File.separator + "groupavata" + originalFilename;
        GroupInfo groupInfo = new GroupInfo();
        groupInfo.setGroupName(groupName);
        groupInfo.setGroupOwner(userId);
        groupInfo.setGroupNotice(groupNotice);
        groupInfo.setJoinType(enumByValue.getValue());
        groupInfo.setAvataUrl(avataUrl);
        // 正常
        groupInfo.setStatus(1);
        boolean save = this.save(groupInfo);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建失败");
        }
        return GroupInfo.objToVo(groupInfo);
    }

    /**
     * 更新群组信息
     *
     * @param groupName
     * @param groupNotice
     * @param enumByValue
     * @param request
     * @param newAvata
     * @return
     */
    @Override
    public Boolean updateGroup(Integer status,Long id, String groupName, String groupNotice, GroupJoinTypeEnum enumByValue, HttpServletRequest request, MultipartFile newAvata) {
        // 获取当前登录用户
        UserInfo loginUser = userInfoService.getLoginUser(request);
        Long userId = loginUser.getId();
        // 校验当前群组是否是当前用户所创建的
        GroupInfo byId = this.getById(id);
        if (byId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "群组不存在");
        }
        if (!byId.getGroupOwner().equals(userId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "只能修改自己创建的群组");
        }
        try {
            newAvata.transferTo(new File(System.getProperty("user.dir") + File.separator + "groupavata" + UUID.randomUUID() + ".jpg"));
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        String avataUrl = "http://localhost:8080/api/groupavata/" + UUID.randomUUID() + ".jpg";
        Integer type = enumByValue.getValue();
        GroupInfo groupInfo = new GroupInfo();
        groupInfo.setId(id);
        groupInfo.setGroupName(groupName);
        groupInfo.setAvataUrl(avataUrl);
        groupInfo.setGroupNotice(groupNotice);
        groupInfo.setJoinType(type);
        groupInfo.setStatus(status);
        boolean b = this.updateById(groupInfo);
        if (!b){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "修改失败");
        }
        return true;
    }

    /**
     * 获取群组信息
     * @param id
     * @param loginUser
     * @return
     */
    @Override
    public GroupInfo getGroupInfo(Long id, UserInfo loginUser) {
        Long userId = loginUser.getId();
        LambdaQueryWrapper<UserContact> lambdaQueryWrapper = Wrappers.lambdaQuery(UserContact.class)
                .eq(UserContact::getId, userId)
                .eq(UserContact::getContactId, id);
        UserContact userContact = userContactService.getOne(lambdaQueryWrapper);
        if (userContact == null || !UserContactStatusEnum.FRIEND.getValue().equals(userContact.getStatus())){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "你不再群聊中或群聊不存在或群聊已解散");
        }
        LambdaQueryWrapper<GroupInfo> queryWrapper = Wrappers.lambdaQuery(GroupInfo.class)
                .eq(GroupInfo::getGroupOwner, userId)
                .eq(GroupInfo::getId, id)
                .eq(GroupInfo::getStatus, 1);
        GroupInfo byId = this.getById(queryWrapper);
        if (byId == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "群聊不存在或已解散");
        }
        return byId;
    }
}




